package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.mapper.LoginMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, username));
        if(login != null){
            List<Permission> permissionList = loginMapper.getCurrentAuth(login.getId());
            List<SimpleGrantedAuthority> collect = permissionList.stream()
                    .map( permission-> new SimpleGrantedAuthority(permission.getSn()))
                    .collect(Collectors.toList());
            // 账号  密码  权限
            String password = login.getPassword();
            login.setPassword("");
            String jsonString = JSONObject.toJSONString(login);
            User user = new User(jsonString,password,collect);
            return user;
        }
        return null;
    }
}
